package com.dong.springboothikaricpmultiple.config;

import com.zaxxer.hikari.HikariDataSource;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.util.StringUtils;

import javax.sql.DataSource;

/**
 * 数据源配置类
 *
 * @author DJ
 * @version 1.0
 * @date 2023/8/2 16:42
 */
@Configuration
public class DataSourceConfig {


    /**
     * 创建orders数据源配置对象
     *
     * @return org.springframework.boot.autoconfigure.jdbc.DataSourceProperties
     * @author DJ
     * @date 2023/8/2 16:45
     */
    @Primary
    @Bean(name = "ordersDataSourceProperties")
    @ConfigurationProperties(prefix = "spring.datasource.orders")
    public DataSourceProperties ordersDataSourceProperties() {
        return new DataSourceProperties();
    }

    /**
     * 创建orders数据源
     *
     * @return javax.sql.DataSource
     * @author DJ
     * @date 2023/8/2 17:55
     */
    @Bean(name = "ordersDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.orders.hikari")
    public DataSource ordersDataSource() {
        DataSourceProperties properties = this.ordersDataSourceProperties();
        return this.createHikariDataSource(properties);
    }

    /**
     * 创建users数据源配置对象
     *
     * @param properties
     * @return com.zaxxer.hikari.HikariDataSource
     * @author DJ
     * @date 2023/8/2 17:58
     */
    @Bean("usersDataSourceProperties")
    @ConfigurationProperties(prefix = "spring.datasource.users")
    public DataSourceProperties usersDataSourceProperties() {
        return new DataSourceProperties();
    }


    /**
     * 创建users数据源
     *
     * @return javax.sql.DataSource
     * @author DJ
     * @date 2023/8/3 10:34
     */
    @Bean("usersDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.users.hikari")
    public DataSource usersDataSource() {
        DataSourceProperties properties = this.usersDataSourceProperties();
        return createHikariDataSource(properties);
    }

    private static HikariDataSource createHikariDataSource(DataSourceProperties properties) {
        // 创建HikariDataSource对象
        HikariDataSource dataSource = properties.initializeDataSourceBuilder().type(HikariDataSource.class).build();
        // 设置线程名称
        if (StringUtils.hasText(properties.getName())) {
            dataSource.setPoolName(properties.getName());
        }
        return dataSource;
    }

}
